use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use std::env;

pub fn converter(input: &str) -> String {
    let dict = init_dict();
    let mut s = String::new();
    for (i, c) in input.chars().enumerate() {
        let c = c.to_string();
        if !dict.contains_key(&c) {
            return "".to_string();
        }
        let k = &dict[&c].clone();
        if i == 0 {
            let mut k: Vec<_> = k.chars().collect();
            k[0] = k[0].to_ascii_uppercase();
            let k: String = k.iter().collect();
            s += &k;
        } else {
            s += " ";
            s += k;
        }
    }
    s
}

fn init_dict() -> HashMap<String, String> {
    let workspace = PathBuf::from(find_workspace_root().unwrap());
    let file_path = "topic1/solutiont4/chinese_pinyin.json";
    let path = workspace.join(file_path);
    let mut file = File::open(path).unwrap();
    let mut json = String::new();
    file.read_to_string(&mut json).unwrap();
    let dict = serde_json::from_str(&json).unwrap();
    dict
}


fn find_workspace_root() -> Option<String> {
    let mut current_dir = env::current_dir().ok()?;
    let cargo_toml_path = current_dir.join("Cargo.toml");
    if cargo_toml_path.is_file() {
        let mut file = File::open(cargo_toml_path).unwrap();
        let mut json = String::new();
        file.read_to_string(&mut json).unwrap();
        if json.contains("[workspace]") {
            return Some(current_dir.to_str().unwrap().to_string());
        }
    }

    while current_dir.parent().is_some() {
        current_dir = current_dir.parent()?.to_path_buf();
        let cargo_toml_path = current_dir.join("Cargo.toml");
        if cargo_toml_path.is_file() {
            let mut file = File::open(cargo_toml_path).unwrap();
            let mut json = String::new();
            file.read_to_string(&mut json).unwrap();
            if json.contains("[workspace]") {
                return Some(current_dir.to_str().unwrap().to_string());
            }
        }
    }

    None
}